#include <stdio.h>
#include <stdlib.h>
#include <time.h>

const int MAX_ITER = 10000, MAX_LENGTH = 10000;
const double PROB = 0.499;

/* define Constants */
int isHeads(double prob);
int performRandomWalk(int initial_state, double Prob);
double findF(double Prob);

int main(int argc, char* argv[]) {

	double f;

	f = findF(atoi(argv[1]));

	printf(" f = %lf \n",f);	

	return EXIT_SUCCESS;
}

double findF(double Prob) {

	int i;
	int state,count;
	double f;

	state = 0;
	count = 0;

	srand(time(NULL));

	for (i=0; i < MAX_ITER; i++) {

		state = performRandomWalk(state, PROB);
		
		if ( state == 0 ) {
			count++;
		}
	
	}

	printf(" count = %d \n", count);
	printf(" Max iterations = %d \n", MAX_ITER);

	/* calculate f */
	f = (double)count / (double)MAX_ITER ;

	return f; 

}

/* returns final state */
int performRandomWalk(int initial_state, double Prob) {

	int j, state = initial_state, trialsCount = 0;

	for (j=0; j < MAX_LENGTH; j++) {

		/* flip coin */
		if ( isHeads(Prob) ) {
			state += 1;
		} else {
			state -= 1;
		}

		trialsCount += 1;

		if ( state == 0 ) {
			break;
		}

	}

	return state;
	
}

int isHeads(double prob) {

	double randNum;

	randNum = (double)rand()/(double)RAND_MAX;
	
	/* printf("%lf \n", randNum); */
	
	return ( (randNum < prob) ? 0 : 1);

}